#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tapclient_datasource.py 
@version:
@time: 2022/06/02 
"""
from TapClientCore.T05_TM_feature.v1.TMF01_datasource.tmf_datasource import *
from TapUtil.decorator.some_useful import timeout


class V1TapclientDataSource(TMFDataSource):

    # 查询所有数据源 database_type: name
    def tap_v1_get_all_connections(self):
        all_connections = []
        response = self._get_connections()
        for one in response:
            all_connections.append({
                one.get('database_type'): f"{one.get('name')}: {one.get('status')}"
            })
        return all_connections

    # 查询所有数据源类型
    def tap_v1_get_all_connections_type(self):
        all_connections_type = {}
        response = self._get_connections()
        for one in response:
            database_type = one.get('database_type')
            if database_type in all_connections_type:
                all_connections_type[database_type] += 1
            else:
                all_connections_type[database_type] = 1
        return all_connections_type

    # 查询
    def tap_v1_get_connections_by_db_type(self, db_type):
        all_connections = {}
        response = self._get_connections()
        for one in response:
            if one.get('database_type') == db_type:
                all_connections.update({
                    one.get('name'): one.get('status')
                })
        return all_connections

    # 查询
    def tap_v1_get_connections_by_name(self, name):
        response = self._get_connections()
        for one in response:
            if one.get('name') == name:
                return one
        return f'Not Found {name}'

    # 创建

    # 修改

    # 删除
    def tap_v1_datasource_remove(self, connections_name):
        self.delete_datasource_by_name(connections_name)

    # 加载schema
    # 数据源test，加载schema，并等待状态为finished
    def tap_v1_datasource_test(self, connections_name):
        self.test_connection_by_name(connections_name)
        self._wait_datasource_status_finished(connections_name)
        self._wait_datasource_status_ready(connections_name)

    # 数据源加载schema，并等待状态为finished
    def tap_v1_datasource_load_schema(self, connections_name):
        self.load_schema_by_name(connections_name)
        self._wait_datasource_status_finished(connections_name)

    # 等待数据源schema状态finished
    @timeout('finished', 200)
    def _wait_datasource_status_finished(self, connections_name):
        response = self.query_datasource_by_name(connections_name)
        return response.get('loadFieldsStatus')

    # 等待数据状态为ready
    @timeout('ready', 200)
    def _wait_datasource_status_ready(self, connections_name):
        response = self.query_datasource_by_name(connections_name)
        return response.get('status')


if __name__ == '__main__':
    T = V1TapclientDataSource()
    print(T.tap_v1_datasource_load_schema('de'))
